// 自定义 Mutex 实现，兼容 Node.js 9.11.2
class CustomMutex {
    constructor() {
        this._locked = false;
        this._queue = [];
    }

    acquire() {
        return new Promise((resolve) => {
            if (!this._locked) {
                this._locked = true;
                resolve(this._release.bind(this));
            } else {
                this._queue.push(resolve);
            }
        });
    }

    _release() {
        if (this._queue.length > 0) {
            const nextResolve = this._queue.shift();
            nextResolve(this._release.bind(this));
        } else {
            this._locked = false;
        }
    }

    runExclusive(callback) {
        return this.acquire().then((release) => {
            return Promise.resolve()
                .then(callback)
                .then(
                    (result) => {
                        release();
                        return result;
                    },
                    (error) => {
                        release();
                        throw error;
                    }
                );
        });
    }

    isLocked() {
        return this._locked;
    }
}
module.exports = CustomMutex;